import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import AdminLayout from '../views/AdminLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: AdminLayout,
    children: [
      { path: '', redirect: '/users' },
      { path: '/users', component: () => import('../views/UserManagement.vue') },
      { path: '/posts', component: () => import('../views/PostManagement.vue') },
      { path: '/chat', component: () => import('../views/ChatManagement.vue') },
      { path: '/review', component: () => import('../views/ReviewManagement.vue') },
      { path: '/comment', component: () => import('../views/CommentManagement.vue') }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

export default router